package com.hundsun.hsOffer.controller;

import com.hundsun.hsOffer.dto.UserDto;
import com.hundsun.hsOffer.model.SysRoles;
import com.hundsun.hsOffer.model.SysUsers;
import com.hundsun.hsOffer.model.UserRoles;
import com.hundsun.hsOffer.utils.Combobox;
import com.hundsun.hsOffer.utils.DataGrid;
import com.hundsun.hsOffer.utils.DateUtils;
import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.tx.Tx;

import java.util.Date;
import java.util.List;

/**
 * Create By IDEA
 * User:giegie
 * Date:2016/9/12
 * Description:用户管理模块
 */
public class UserController extends Controller {
    /**
     * 显示全部用户
     */
    public void userListUI() {
        renderFreeMarker("userList.ftl");
    }

    public void userList() {
        DataGrid<UserDto> dataGrid = SysUsers.dao.findByPage(getParaToInt("page"), getParaToInt("rows"));
        renderJson(dataGrid);
    }

    public void userAddUI() {
        renderFreeMarker("userAdd.ftl");
    }

    public void addUser() {
        String result = "";
        SysUsers user = getModel(SysUsers.class, "", true);
        user.setCreateTime(DateUtils.formatDateTime(new Date()));
        boolean saveResult = user.saveUser(user);
        if (saveResult){
            SysUsers  sysUser = SysUsers.dao.findByUserName(user.getUsername());
            Integer[] userRoles = getParaValuesToInt("userRoles");
            for (int roleId : userRoles){
                UserRoles userRole = new UserRoles();
                userRole.setUserId(sysUser.getUserId());
                userRole.setRoleId(roleId);
                userRole.save();
            }
            result = "保存成功";
        }else {
            result = "用户名已经存在";
        }
        renderJson(result);
    }

    public void delUser(){
        int userId = getParaToInt(0);
        renderJson(SysUsers.dao.deleteById(userId));
    }

    public void roleListUI() {
        renderFreeMarker("roleList.ftl");
    }

    public void roleList() {
        DataGrid<SysRoles> sysRolesDataGrid = SysRoles.dao.findByPage(getParaToInt("page"), getParaToInt("rows"));
        renderJson(sysRolesDataGrid);
    }

    public void findRoles(){
        List<Combobox> roles  = SysRoles.dao.findAll();
        renderJson(roles);
    }
}
